
package com.liuzh.websocket.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;


/**
 * Socket建立连接（握手）和断开
 */
public class HandShake implements HandshakeInterceptor {

	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
			WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
		
		String msg = null;
		boolean chain = false;
		
		if (request instanceof ServletServerHttpRequest) {
			
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			
			HttpSession session = servletRequest.getServletRequest().getSession(false);

			// 标记用户
			Long uid = null;
			
			if( (msg = "ws session 为空！") != null && session != null && (msg = "uid 为空!") != null && ( uid = (Long) session.getAttribute("uid") ) !=null ){
				attributes.put("uid", uid);
				msg = "Websocket:用户[ID:" + session.getAttribute("uid") + "]已经建立连接";
				chain = true;
			}else{
				chain = false;
			}
			
		}else {
			msg = "websocket 连接创建失败！request 类型不匹配";
			chain = false;
		}
		
		System.out.println(msg);
		
		return chain;
	}

	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
		System.out.println("after hand");
	
	}

}
